package logic

import (
	"cart_srv/cart"
	"cart_srv/internal/svc"
	"cart_srv/model/mysql"
	"cart_srv/model/redis"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cart.CartAddRequest) (*cart.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	var good mysql.Goods
	mysql.DB.Where("id=?", in.GoodsId).Limit(1).Find(&good)
	err := mysql.DB.Where("id=?", in.GoodsId).Limit(1).Find(&good).Error
	if good.ID == 0 {
		logx.Error("该商品不存在", err)
		return nil, err
	}
	num := redis.GetGoodsLen(in.GoodsId)
	if num < in.GoodsNum {
		logx.Error("库存不足", err)
		return nil, err
	}
	if !redis.GoodsIsExists(in.UserId, in.GoodsId) {
		goodsCart := mysql.GoodsCart{
			GoodsId:    int(in.GoodsId),
			UserId:     int(in.UserId),
			GoodsName:  good.GoodsName,
			GoodsPrice: good.GoodsPrice,
			GoodsCover: good.GoodsCover,
			GoodsNum:   int(in.GoodsNum),
			Checked:    1,
		}
		redis.SyncCart(&goodsCart)
	} else {
		redis.UpdateGoodsNum(in.UserId, in.GoodsId, in.GoodsNum)
	}
	return &cart.CartAddResponse{}, nil
}
